// 简化版Chart.js库模拟
// 提供基础的图表绘制功能，用于演示实时数据监控系统

window.Chart = (function() {
    // 图表类型常量
    const CHART_TYPES = {
        LINE: 'line',
        BAR: 'bar',
        PIE: 'pie',
        DOUGHNUT: 'doughnut',
        RADAR: 'radar',
        POLAR_AREA: 'polarArea',
        SCATTER: 'scatter'
    };

    // 颜色配置
    const DEFAULT_COLORS = [
        'rgba(102, 126, 234, 0.8)',
        'rgba(118, 75, 162, 0.8)',
        'rgba(255, 99, 132, 0.8)',
        'rgba(54, 162, 235, 0.8)',
        'rgba(255, 206, 86, 0.8)',
        'rgba(75, 192, 192, 0.8)',
        'rgba(153, 102, 255, 0.8)',
        'rgba(255, 159, 64, 0.8)'
    ];

    // 主Chart类
    class Chart {
        constructor(canvas, config) {
            this.canvas = canvas;
            this.ctx = canvas.getContext('2d');
            this.config = config || {};
            this.type = config.type || CHART_TYPES.LINE;
            this.data = config.data || { labels: [], datasets: [] };
            this.options = config.options || {};
            
            // 初始化图表尺寸
            this.resizeCanvas();
            window.addEventListener('resize', () => this.resizeCanvas());
            
            // 开始绘制
            this.draw();
        }

        resizeCanvas() {
            const container = this.canvas.parentElement;
            if (container) {
                this.canvas.width = container.clientWidth;
                this.canvas.height = container.clientHeight || 300;
            }
        }

        draw() {
            // 清空画布
            this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
            
            // 根据图表类型调用相应的绘制方法
            switch (this.type) {
                case CHART_TYPES.LINE:
                    this.drawLineChart();
                    break;
                case CHART_TYPES.BAR:
                    this.drawBarChart();
                    break;
                case CHART_TYPES.PIE:
                    this.drawPieChart();
                    break;
                default:
                    this.drawLineChart();
            }
        }

        drawLineChart() {
            const { labels, datasets } = this.data;
            const { width, height } = this.canvas;
            const padding = 40;
            const chartWidth = width - 2 * padding;
            const chartHeight = height - 2 * padding;
            
            // 绘制坐标轴
            this.drawAxes(padding, padding, chartWidth, chartHeight);
            
            // 绘制网格线
            this.drawGridLines(padding, padding, chartWidth, chartHeight, labels.length);
            
            // 绘制数据系列
            datasets.forEach((dataset, index) => {
                this.drawLineDataset(dataset, index, padding, padding, chartWidth, chartHeight, labels.length);
            });
            
            // 绘制图例
            this.drawLegend(padding, height - padding + 10);
        }

        drawAxes(x, y, width, height) {
            this.ctx.beginPath();
            this.ctx.strokeStyle = '#e9ecef';
            this.ctx.lineWidth = 2;
            
            // X轴
            this.ctx.moveTo(x, y + height);
            this.ctx.lineTo(x + width, y + height);
            
            // Y轴
            this.ctx.moveTo(x, y);
            this.ctx.lineTo(x, y + height);
            
            this.ctx.stroke();
        }

        drawGridLines(x, y, width, height, labelCount) {
            this.ctx.strokeStyle = '#f0f0f0';
            this.ctx.lineWidth = 1;
            this.ctx.setLineDash([5, 5]);
            
            // 垂直网格线
            const xStep = width / (labelCount - 1 || 1);
            for (let i = 0; i < labelCount; i++) {
                const gridX = x + i * xStep;
                this.ctx.beginPath();
                this.ctx.moveTo(gridX, y);
                this.ctx.lineTo(gridX, y + height);
                this.ctx.stroke();
            }
            
            // 水平网格线 (5条)
            const yStep = height / 4;
            for (let i = 0; i <= 4; i++) {
                const gridY = y + i * yStep;
                this.ctx.beginPath();
                this.ctx.moveTo(x, gridY);
                this.ctx.lineTo(x + width, gridY);
                this.ctx.stroke();
            }
            
            this.ctx.setLineDash([]);
        }

        drawLineDataset(dataset, index, x, y, width, height, labelCount) {
            const data = dataset.data || [];
            if (data.length === 0) return;
            
            const color = dataset.backgroundColor || dataset.borderColor || DEFAULT_COLORS[index % DEFAULT_COLORS.length];
            const borderWidth = dataset.borderWidth || 2;
            
            // 计算数据范围
            const minValue = Math.min(...data);
            const maxValue = Math.max(...data);
            const valueRange = maxValue - minValue || 1;
            
            // 绘制线条
            this.ctx.beginPath();
            this.ctx.strokeStyle = color;
            this.ctx.lineWidth = borderWidth;
            this.ctx.lineCap = 'round';
            this.ctx.lineJoin = 'round';
            
            const xStep = width / (data.length - 1 || 1);
            data.forEach((value, i) => {
                const px = x + i * xStep;
                const py = y + height - ((value - minValue) / valueRange) * height;
                
                if (i === 0) {
                    this.ctx.moveTo(px, py);
                } else {
                    this.ctx.lineTo(px, py);
                }
            });
            
            this.ctx.stroke();
            
            // 绘制数据点
            if (dataset.pointRadius !== 0) {
                data.forEach((value, i) => {
                    const px = x + i * xStep;
                    const py = y + height - ((value - minValue) / valueRange) * height;
                    
                    this.ctx.beginPath();
                    this.ctx.arc(px, py, dataset.pointRadius || 4, 0, 2 * Math.PI);
                    this.ctx.fillStyle = color;
                    this.ctx.fill();
                });
            }
        }

        drawBarChart() {
            const { labels, datasets } = this.data;
            const { width, height } = this.canvas;
            const padding = 40;
            const chartWidth = width - 2 * padding;
            const chartHeight = height - 2 * padding;
            
            this.drawAxes(padding, padding, chartWidth, chartHeight);
            this.drawGridLines(padding, padding, chartWidth, chartHeight, labels.length);
            
            const barWidth = (chartWidth / labels.length) / (datasets.length + 1);
            
            datasets.forEach((dataset, datasetIndex) => {
                const data = dataset.data || [];
                const color = dataset.backgroundColor || DEFAULT_COLORS[datasetIndex % DEFAULT_COLORS.length];
                
                const minValue = Math.min(...data);
                const maxValue = Math.max(...data);
                const valueRange = maxValue - minValue || 1;
                
                data.forEach((value, i) => {
                    const barHeight = ((value - minValue) / valueRange) * chartHeight;
                    const x = padding + i * (barWidth * (datasets.length + 1)) + barWidth * datasetIndex;
                    const y = padding + chartHeight - barHeight;
                    
                    this.ctx.fillStyle = color;
                    this.ctx.fillRect(x, y, barWidth, barHeight);
                });
            });
            
            this.drawLegend(padding, height - padding + 10);
        }

        drawPieChart() {
            const { datasets } = this.data;
            const { width, height } = this.canvas;
            const centerX = width / 2;
            const centerY = height / 2;
            const radius = Math.min(width, height) / 3;
            
            if (datasets.length === 0 || datasets[0].data.length === 0) return;
            
            const data = datasets[0].data;
            const total = data.reduce((sum, value) => sum + value, 0);
            let startAngle = -Math.PI / 2;
            
            data.forEach((value, index) => {
                const sliceAngle = (value / total) * 2 * Math.PI;
                const endAngle = startAngle + sliceAngle;
                const color = datasets[0].backgroundColor ? 
                    (Array.isArray(datasets[0].backgroundColor) ? 
                        datasets[0].backgroundColor[index] : datasets[0].backgroundColor) : 
                    DEFAULT_COLORS[index % DEFAULT_COLORS.length];
                
                // 绘制扇形
                this.ctx.beginPath();
                this.ctx.moveTo(centerX, centerY);
                this.ctx.arc(centerX, centerY, radius, startAngle, endAngle);
                this.ctx.closePath();
                this.ctx.fillStyle = color;
                this.ctx.fill();
                
                // 绘制边框
                this.ctx.strokeStyle = 'white';
                this.ctx.lineWidth = 2;
                this.ctx.stroke();
                
                startAngle = endAngle;
            });
            
            this.drawLegend(width - 150, 50);
        }

        drawLegend(x, y) {
            const { datasets } = this.data;
            const legendItemHeight = 20;
            let legendY = y;
            
            datasets.forEach((dataset, index) => {
                const label = dataset.label || `数据集 ${index + 1}`;
                const color = dataset.backgroundColor || dataset.borderColor || DEFAULT_COLORS[index % DEFAULT_COLORS.length];
                
                // 绘制颜色方块
                this.ctx.fillStyle = color;
                this.ctx.fillRect(x, legendY, 12, 12);
                
                // 绘制标签
                this.ctx.fillStyle = '#333';
                this.ctx.font = '12px Arial';
                this.ctx.fillText(label, x + 18, legendY + 10);
                
                legendY += legendItemHeight;
            });
        }

        update(newConfig) {
            if (newConfig) {
                this.data = newConfig.data || this.data;
                this.options = newConfig.options || this.options;
            }
            this.draw();
        }

        destroy() {
            window.removeEventListener('resize', () => this.resizeCanvas());
            this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
        }
    }

    // 工具方法
    Chart.helpers = {
        generateColors: (count) => {
            const colors = [];
            for (let i = 0; i < count; i++) {
                colors.push(DEFAULT_COLORS[i % DEFAULT_COLORS.length]);
            }
            return colors;
        }
    };

    // 注册图表类型
    Chart.defaults = {
        responsive: true,
        maintainAspectRatio: false
    };

    return Chart;
})();